// 思路：将要排序数组进行二分，然后根据左右两边的大小进行排序合并

function mergeSort(arr) {
  if (arr.length < 2) {
    return arr
  }
  const mid = Math.floor(arr.length / 2)
  let left = mergeSort(arr.slice(0, mid))
  let right = mergeSort(arr.slice(mid))

  return merge(left, right)
}

function merge(left, right) {
  // left指针
  let i = 0;
  // right指针
  let j = 0;
  let res = []
  while (i < left.length && j < right.length) {
    if (left[i] <= right[j]) {
      res.push(left[i])
      i++
    } else {
      res.push(right[j])
      j++
    }
  }
  if (i < left.length) {
    res.push(...left.slice(i))
  } else {
    res.push(...right.slice(j))
  }
  return res
}

console.log(mergeSort([4, 2, 5, 3, 6, 1, 3, 8]));